package com.ch.d0312.d0316;

import com.ch.util.DBHelper;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryBook1Servlet", value = "/QueryBook1Servlet.s")
public class QueryBook1Servlet extends HttpServlet {



    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        final String bookname = request.getParameter("bookname");
        final String bookauthor = request.getParameter("bookauthor");

        final String pageSize = request.getParameter("pageSize");
        final String currentPage = request.getParameter("currentPage");
        System.out.println(bookauthor);
        System.out.println(bookname);
        System.out.println(pageSize);
        System.out.println(currentPage);
        int size = Integer.valueOf(pageSize);
        int page = Integer.valueOf(currentPage);
        int begin = size * (page - 1);

        String sql = "select * from bm_book where 1=1";

        // 组合条件查询
        List<Object> params = new ArrayList<>();
        if(bookname != null && bookname.trim().isEmpty() == false){
            sql += " and bookname like ?";
            params.add("%" + bookname + "%");
        }
        if(bookname != null && bookauthor.trim().isEmpty() == false){
            sql += " and bookauthor like ?";
            params.add("%" + bookauthor + "%");
        }

        System.out.println(sql);
        // 查询总页数
        final long total = DBHelper.count(sql,params.toArray());

        params.add(begin);
        params.add(size);

        // 查询当前页的数据
        final List<Map<String,Object>> data =
                DBHelper.selectListMap(sql + " limit ?,? ",params.toArray());

        Map<String,Object> result = new HashMap<>();
        result.put("data",data);
        result.put("total",total);
        final  String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    }
}
